'''
Created on 09/04/2009

@author: eh01
'''
from yarra.datastore import dsconstants, dsofactory
from yarra.datastore.dsstub import DSStub
from yarra.event import eventconstants
from yarra.event.event import Event
from yarra.event.eventhandler import BaseEventHandler
from yarra.event.eventmanager import EventManager
from yarra.logindecorator import loginRequired
import httplib
import re


class HTTPRequestGETNodeMessageHandler(BaseEventHandler):

    @loginRequired
    def do(self, data):
        dso = data
        http_request = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_HTTP_REQUEST).get_literal()
        lock = dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                    predicate=dsconstants.PREDICATE_LOCK).get_literal()                    
        
        matches = re.match('/node/(\d+)/(\d+)$', http_request.path)
        
        node_id = int(matches.group(1))
        message_id = int(matches.group(2))
                
        ds_stub = DSStub()
        message_dso = ds_stub.get_message(node_id, message_id)
        
        if message_dso:
            content_type = message_dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                                predicate=dsconstants.PREDICATE_CONTENT_TYPE).get_literal()
            response_body = message_dso.get_dst(subject=dsconstants.SUBJECT_ROOT,
                                predicate=dsconstants.PREDICATE_BODY).get_literal()
            
            # create new dso        
            new_dso = dsofactory.create_dso_for_im_http_response_handler(httplib.OK, 
                                                                   content_type, 
                                                                   response_body, 
                                                                   http_request, 
                                                                   lock)
            event_type = eventconstants.HTTP_RESPONSE_EVENT_TYPE            
        else:
            new_dso = dsofactory.create_dso_for_http_error_handler(httplib.NOT_FOUND, 
                                                                   None, 
                                                                   http_request, 
                                                                   lock)
            event_type = eventconstants.HTTP_ERROR_EVENT_TYPE
        event = Event(event_type, new_dso)
        EventManager().add_event(event)        
                